package cn.ryanpenn.es.ms.weather.service.impl;

import cn.ryanpenn.es.ms.weather.model.WeatherResponse;
import cn.ryanpenn.es.ms.weather.service.WeatherService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * WeatherServiceImpl
 *
 * @author pennryan
 */
@Service
public class WeatherServiceImpl implements WeatherService {

    private final String WEATHER_BYKEY_API = "http://wthrcdn.etouch.cn/weather_mini?citykey=";

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public WeatherResponse getByCityCode(String code) {

        String key = WEATHER_BYKEY_API + code;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        if (stringRedisTemplate.hasKey(key)) {
            String bodyStr = ops.get(key);
            if (!StringUtils.isEmpty(bodyStr)) {
                try {
                    return new ObjectMapper().readValue(bodyStr, WeatherResponse.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }
}
